<template>
    <div class="search-unit">
        <el-autocomplete
            v-model="state"
            value-key="title"
            :fetch-suggestions="querySearchAsync"
            :select-when-unmatched="false"
            placeholder="发现什么"
            @select="handleSelect"
        />
        <el-button :icon="Search" @click="searchBlogs" />
    </div>
</template>

<script>
import { ref, reactive } from '@vue/reactivity'
import { onMounted } from '@vue/runtime-core'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import router from '@/router'

export default {
    name: 'SearchUnit',
    setup() {
        let state = ref('')
        let data = reactive([])
        let timeout = null//接收定时器
        const loadAll = async () => {
            return new Promise((resolve, reject) => {
                axios.get('http://localhost/api/getBlog').then(res => {
                    resolve(res.data)
                }).then(err => {
                    reject(err)
                }) 
            }).catch(err => {
                console.log('未知错误！')
                console.log(err)
            })
        }
        const querySearchAsync = (queryString, cb) => {
            //console.log(data)
            const results = queryString ? data.filter(createFilter(queryString)) : data
            clearTimeout(timeout)//解除定时器
            timeout = setTimeout(() => {
                cb(results)
            }, 1500 * Math.random())
        }
        //这个应该是数组里的对象的搜索规则
        const createFilter = (queryString) => {
            return (data) => {
                return data.title.toLowerCase().includes(queryString.toLowerCase())//是子串就符合
            }
        }
        //选择搜索项后触发
        const handleSelect = (item) => {
            console.log(item)
            router.push(`/blog/${item.id}`)
        }
        const searchBlogs = () => {
            if(state.value) {
                router.push({
                    path: '/passage',
                    query: {
                        state: state.value
                    }
                })
            } else {
                router.push('/passage')
            }
        }

        onMounted(async () => {
            data.splice(0, data.length, ...await loadAll())//我是聪明b，哈哈！
            //console.log(data)
        })

        return {
            state,
            data,
            querySearchAsync,
            handleSelect,
            searchBlogs,
            Search
        }
    }
}
</script>

<style scoped>
    .search-unit {
        display: flex;
        justify-content: center;
        align-items: center;
        min-width: 300px;
    }
    .el-button {
        width: 35px;
        margin: 0 2px;
    }
</style>